//                       .::::.
//                     .::::::::.
//                    :::::::::::
//                 ..:::::::::::'
//              '::::::::::::'
//                .::::::::::
//           '::::::::::::::..
//                ..::::::::::::.
//              ``::::::::::::::::
//               ::::``:::::::::'        .:::.
//              ::::'   ':::::'       .::::::::.
//            .::::'      ::::     .:::::::'::::.
//           .:::'       :::::  .:::::::::' ':::::.
//          .::'        :::::.:::::::::'      ':::::.
//         .::'         ::::::::::::::'         ``::::.
//     ...:::           ::::::::::::'              ``::.
//    ```` ':.          ':::::::::'                  ::::..
//                       '.:::::'                    ':'````..
package com.xw.controller.manage;

import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.xw.common.Const;
import com.xw.model.DicGroupLimit;
import com.xw.model.Videos;
import com.xw.model.VideosItem;
import com.xw.service.*;
import com.xw.service.sysconfig.DicGroupLimitService;
import com.xw.service.tool.oss.OssService;
import com.xw.util.AppUtil;
import com.xw.util.JsonData;
import com.xw.util.JsonUtil;
import com.xw.util.PropertiesUtil;
import com.xw.vo.TypeVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Controller
@RequestMapping("/manage/videos/")
@Scope("prototype")
public class VideosController {
    @Resource
    private VideosService videosService;
    @Resource
    private VideosItemService videosItemService;
    @Resource
    private IVideosInfoService videosInfoService;
    @Resource
    private DicGroupLimitService groupLimitService;
    @Resource
    private SysTypeService typeService;
    @Resource
    private OrdersService ordersService;
    @Resource
    private OssService ossService;


    Map<String, Object> map = null;

    /**
     * 根据videoId查询已售出的订单
     *
     * @param videoId
     * @return
     */
    @RequestMapping(value = "findOrdersByPublishVideoId", method = RequestMethod.GET)
    public String findOrdersByPublishVideoId(HttpServletRequest request, String videoId) {
        request.setAttribute("videoId", videoId);
        return "orders/listPublishVideoId";
    }


    @RequestMapping(value = "findOrdersByPublishVideoIdJson", method = RequestMethod.GET)
    @ResponseBody
    public Object findOrdersByPublishVideoIdJson(String videoId, Integer page, Integer limit) {
        Map map = ordersService.findOrdersByPublishVideoIdJson(videoId, page, limit);
        return map;
    }


    @RequestMapping(value = "goEdit", method = RequestMethod.GET)
    public String goEdit(HttpServletRequest request, String glId, String videoId) {
        //查询所有分类
        List<TypeVo> typeList = typeService.findAll();
        //查询该子导航的增删改查的权限
        DicGroupLimit model = groupLimitService.queryByUUID(glId);
        request.setAttribute("model", model);
        request.setAttribute("typeList", typeList);
        request.setAttribute("videoId", videoId);
        request.setAttribute("url", PropertiesUtil.getProperty("URL"));
        return "videos/editType";
    }

    /**
     * 通过
     *
     * @param videoId
     * @return
     */
    @RequestMapping(value = "pass", method = RequestMethod.POST)
    @ResponseBody
    public Map pass(String videoId) {
        Map map = videosService.pass(videoId);
        return map;
    }

    /**
     * 不通过
     *
     * @return
     */
    @RequestMapping(value = "noPass", method = RequestMethod.POST)
    @ResponseBody
    public Map noPass(Videos videos) {
        Map map = videosService.noPass(videos);
        return map;
    }

    /**
     * 跳转到审核不通过页面
     *
     * @param request
     * @param videoId
     * @return
     */
    @RequestMapping(value = "toNoPass", method = RequestMethod.GET)
    public String toNoPass(HttpServletRequest request, String videoId) {
        request.setAttribute("videoId", videoId);
        return "videos/noPass";
    }


    @RequestMapping(value = "updateType", method = RequestMethod.POST)
    @ResponseBody
    public Map updateType(Videos videos) {
        Map map = videosService.updateType(videos);
        return map;
    }

    /**
     * 下架
     *
     * @return
     */
    @RequestMapping(value = "del", method = RequestMethod.POST)
    @ResponseBody
    public Map del(String videoId) {
        Map map = videosService.del(videoId);
        return map;
    }
    /**
     * 上架
     *
     * @return
     */
    @RequestMapping(value = "up", method = RequestMethod.POST)
    @ResponseBody
    public Map up(String videoId) {
        Map map = videosService.up(videoId);
        return map;
    }

    /**
     * 跳转到列表页面
     *
     * @return
     */
    @RequestMapping(value = "findAll", method = RequestMethod.GET)
    public String findAll(HttpServletRequest request, String glId) {
        //查询所有分类
        List<TypeVo> typeList = typeService.findAll();
        //查询该子导航的增删改查的权限
        DicGroupLimit model = groupLimitService.queryByUUID(glId);
        request.setAttribute("model", model);
        request.setAttribute("typeList", typeList);
        request.setAttribute("url", PropertiesUtil.getProperty("URL"));
        return "videos/list";
    }

    /**
     * 获取列表数据
     *
     * @return
     */
    @RequestMapping(value = "findAllJson", method = RequestMethod.GET)
    @ResponseBody
    public Object findAllJson(String videoName, String stIdOne, String stIdTwo, String stIdThree, Integer page, Integer limit,Integer checkStatus,Integer isDel) {
        Map map = videosService.findByWhere(videoName, stIdOne, stIdTwo, stIdThree, page, limit,checkStatus,isDel);
        return map;
    }


    /**
     * 根据课程id查询课程视频
     *
     * @param userId
     * @param videoId
     * @return
     */
    @RequestMapping(value = "findVideoItemsByVideoId", method = RequestMethod.GET)
    public Object findVideoItemsByVideoId(HttpServletRequest request, String userId, String videoId) {
        //判断传参
        Map map = Maps.newHashMap();
        // map.put("userId", userId);
        map.put("videoId", videoId);
        String str = AppUtil.checkIsNull(map);
        if (!str.equals(Const.SUCCESS_CODE_STR)) {
            return JsonData.fail(Const.parameterError(str));
        }
        map.clear();
        map = videosService.findVideosByVideoId(userId, videoId);
        System.out.println(map);
        request.setAttribute("data", map.get("data"));
        return "videos/tryVideoItemId";
    }

    @RequestMapping(value = "addTryVideoItemsToVideoId", method = RequestMethod.POST)
    @ResponseBody
    public Object addTryVideoItemsToVideoId(String videoItemId, String videoId) {
        //判断传参
        Map map = Maps.newHashMap();
        map.put("videoItemId", videoItemId);
        map.put("videoId", videoId);
        String str = AppUtil.checkIsNull(map);
        if (!str.equals(Const.SUCCESS_CODE_STR)) {
            return JsonData.fail(Const.parameterError(str));
        }
        map.clear();
        map = videosService.addTryVideoItemsToVideoId(videoItemId, videoId);
        System.out.println(map);
        // request.setAttribute("data",map.get("data"));
        return map;
    }


    /**
     * 上传视频并创建课程将视频添加到课程
     *
     * @param
     * @return uploadFileToOSS
     * @throws IOException
     */
    @RequestMapping(value = "/uploadFileToOSS", method = RequestMethod.POST)
    @ResponseBody
    public Object uploadFileToOSS(String userId, String videoName, String teacherName, String stIdOne, String stIdTwo, String videoDesc,
                                  String videoImg, Integer isFree, Double originalPrice, Double currentPrice, Integer publishType, String videoItemName, String videoId,
                                  String updateVideoItem,String addVideoItem,String addVideoItemUrlData) throws IOException {

        String videoIdStart = null;
        if ("" != videoId && null != videoId && !videoId.equals("0")) {
            videoIdStart = videoId;
        }
        if (StringUtils.equals("-1",videoId)) {
            Map map = Maps.newHashMap();
            map.put("userId", userId);
            map.put("videoName", videoName);
            map.put("teacherName", teacherName);
            map.put("stIdOne", stIdOne);
            map.put("stIdTwo", stIdTwo);
            map.put("videoDesc", videoDesc);
            map.put("isFree", isFree);
            map.put("publishType", publishType);
            String str = AppUtil.checkIsNull(map);
            if (!str.equals(Const.SUCCESS_CODE_STR)) {
                return JsonData.fail(Const.parameterError(str));
            }
            if (isFree != 1) {
                if (originalPrice < 0) {
                    return JsonData.fail("售价请输入大于0的正数(保留两位小数)");
                }
            }
            currentPrice = originalPrice;
            map = videosService.createUpdateVideo(userId, videoName, teacherName, stIdOne, stIdTwo, videoDesc, videoImg, isFree, originalPrice, currentPrice, publishType);
            if (null == map) {
                return JsonData.fail(Const.OPREATE_MSG_ERROR);
            }
            videoIdStart = map.get("videoId").toString();
        }else{
            //添加已有课程，修改排序
          if (StringUtils.isNotBlank(updateVideoItem)){
              List<VideosItem> list = JsonUtil.string2Obj(updateVideoItem, new TypeReference<List<VideosItem>>() {
              });
              if (CollectionUtils.isNotEmpty(list)){
                  videosItemService.updateVideosItem(videoId,list);
              }
          }
        }

        map = Maps.newHashMap();
        List<String> url = Splitter.on(",").splitToList(addVideoItemUrlData);
        //上传列表中的数据名称，排序
        List<VideosItem> list = JsonUtil.string2Obj(addVideoItem, new TypeReference<List<VideosItem>>() {
        });
        for (int i = 0; i < list.size(); i++) {
            VideosItem videosItem = list.get(i);
            String videoItemUrl = url.get(i);
            Integer sort = videosItem.getSort();
            videosItemService.insertVideoItem(videosItem.getVideoItemName(), videoItemUrl, videoIdStart, userId,sort);
        }

        map.clear();
        map.put("videoId", videoIdStart);
        return JsonData.success(map.get("videoId"), Const.OPREATE_MSG_SUCCESS);
    }

    /**
     * 上传课程封面
     *
     * @param
     * @return uploadVideoInfoToOSS
     * @throws IOException
     */
    @RequestMapping(value = "/uploadVideoImgToOSS", method = RequestMethod.POST)
    @ResponseBody
    public Object uploadVideoImgToOSS(MultipartHttpServletRequest request) throws IOException {

        String videoImgUrl = null;
        map = Maps.newHashMap();
        Iterator<String> fileNames = request.getFileNames();
        while (fileNames.hasNext()) {
            //把fileNames集合中的值打出来
            String fileName = fileNames.next();
            System.out.println("fileName: " + fileName);
            MultipartFile file = request.getFile(fileName);
            map = ossService.upload(file);
            videoImgUrl = map.get("url").toString();
        }
        System.out.println("------------------videoImgUrl--------------" + videoImgUrl);
        return JsonData.success(map.get("url"), Const.OPREATE_MSG_SUCCESS);
    }


    /**
     * 上传课程资料
     *
     * @param
     * @return uploadVideoInfo
     * @throws IOException
     */
    @RequestMapping(value = "/uploadVideoInfo", method = RequestMethod.POST)
    @ResponseBody
    public Object uploadVideoInfoToOSS(MultipartHttpServletRequest request,String videoId,String userId,String sort) throws IOException {

        String videoInfoUrl = null;
        String videoInfoName = null;
        Integer videoInfoSort = Integer.parseInt(sort);
        map = Maps.newHashMap();
        Iterator<String> fileNames = request.getFileNames();
        while (fileNames.hasNext()) {
            //把fileNames集合中的值打出来
            String fileName = fileNames.next();
            System.out.println("fileName: " + fileName);
            MultipartFile file = request.getFile(fileName);
            videoInfoName = file.getOriginalFilename();
            map = ossService.upload(file);
            videoInfoUrl = map.get("url").toString();
        }
        return videosInfoService.insertVideoInfo(userId,videoId,videoInfoSort,videoInfoName,videoInfoUrl);
    }


}
